﻿using System;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Collections;

namespace Texpro
{
    public partial class FMTR601 : Form
    {

        public FMTR601()
        {
            InitializeComponent();
        }

        private void FMTR601_Load(object sender, EventArgs e)
        {
            UseWaitCursor = true;
            lbl_form_title.Text = this.Text;
            load_form();
            UseWaitCursor = false;
        }

        private void clear_fields()
        {
            dt_payment_date.Value = PCPUB.m_tran_date;
            PCPUB.m_fill_combo(lst_vendor, "NONE");
            lst_vendor_type.SelectedIndex = -1;
            lst_vendor.SelectedIndex = -1;
            txt_payment_id.Text = String.Empty;
            txt_amount.Text = String.Empty;
            txt_remarks.Text = String.Empty;
            dgv_detail.Rows.Clear();
            switch (PCPUB.m_entry_form_mode)
            {
                case "ADDNEW":
                    dt_payment_date.Enabled = false;
                    lst_vendor_type.Enabled = true;
                    lst_vendor.Enabled = true;
                    lst_vendor_type.Focus();
                    break;
                case "EDIT":
                    dt_payment_date.Enabled = false;
                    fill_form_data_edit(PCPUB.m_record_date, PCPUB.m_record_id);
                    lst_vendor_type.Enabled = false;
                    lst_vendor.Enabled = false;
                    dgv_detail.Focus();
                    break;
            }
        }

        private void fill_form_data_addnew(string p_vendor_type_id, string p_vendor_id)
        {
            String strQuery = String.Empty;
            OleDbConnection sqlConn = new OleDbConnection();
            OleDbCommand sqlComm = new OleDbCommand();
            OleDbDataReader sqlRead;
            String vendor_type_id = String.Empty;
            String vendor_id = String.Empty;
            String tran_type_id = String.Empty;
            String payment_date = "'" + PCPUB.m_get_sql_date(dt_payment_date) + "'";
            //
            vendor_type_id = p_vendor_type_id;
            vendor_id = p_vendor_id;
            switch (vendor_type_id.ToString())
            {
                case "DYER":
                    tran_type_id = "FMTR202";
                    break;
                case "WEAVER":
                    tran_type_id = "FMTR302";
                    break;
                case "WASHER":
                    tran_type_id = "FMTR402";
                    break;
                case "TAILOR":
                    tran_type_id = "FMTR502";
                    break;
            }
            //
            sqlConn.ConnectionString = PCPUB.m_oledb_connection.ToString();
            sqlConn.Open();
            //
            strQuery = String.Empty;
            strQuery += " SELECT ";
            strQuery += " [tran_type_id],";
            strQuery += " [tran_type_name],";
            strQuery += " [tran_date],";
            strQuery += " [tran_id],";
            strQuery += " [amount_gross],";
            strQuery += " [amount_nett],";
            strQuery += " [amount_paid]";
            strQuery += " FROM [vw_payment_status]";
            strQuery += " WHERE [vendor_type_id] = '" + vendor_type_id.ToString() + "'";
            strQuery += " AND [vendor_id] = '" + vendor_id.ToString() + "'";
            strQuery += " AND [tran_type_id] = '" + tran_type_id.ToString() + "'";
            strQuery += " AND ISNULL([payment_id],'NOTPAID') = 'NOTPAID'";
            strQuery += " AND [tran_date] <= " + payment_date;
            strQuery += " ORDER BY [tran_date],[tran_id]";
            //
            sqlComm = new OleDbCommand();
            sqlComm.Connection = sqlConn;
            sqlComm.CommandText = strQuery.ToString();
            sqlRead = sqlComm.ExecuteReader();
            //
            dgv_detail.Rows.Clear();
            int r = -1;
            while (sqlRead.Read())
            {
                dgv_detail.Rows.Add();
                r++;
                dgv_detail["col_tran_date", r].Value = sqlRead["tran_date"].ToString();
                dgv_detail["col_tran_id", r].Value = sqlRead["tran_id"].ToString();
                dgv_detail["col_tran_type_id", r].Value = sqlRead["tran_type_id"].ToString();
                dgv_detail["col_tran_type_name", r].Value = sqlRead["tran_type_name"].ToString();
                dgv_detail["col_amount_gross", r].Value = sqlRead["amount_gross"].ToString();
                dgv_detail["col_amount_nett", r].Value = sqlRead["amount_nett"].ToString();
                dgv_detail["col_amount_paid", r].Value = sqlRead["amount_nett"].ToString();
                dgv_detail["col_select", r].Value = "FALSE";
            }
            //
            sqlRead.Close();
            sqlConn.Close();
            sqlRead.Dispose();
            sqlComm.Dispose();
            sqlConn.Dispose();
        }

        private void fill_form_data_edit(string p_date, string p_id)
        {
            String strQuery = String.Empty;
            OleDbConnection sqlConn = new OleDbConnection();
            OleDbCommand sqlComm = new OleDbCommand();
            OleDbDataReader sqlRead;// = new OleDbDataReader();
            DateTime strReturn = DateTime.Now;
            //           
            sqlConn.ConnectionString = PCPUB.m_oledb_connection.ToString();
            sqlConn.Open();
            //
            strQuery = String.Empty;
            strQuery += " SELECT [payment_date] payment_date,";
            strQuery += " [payment_id] payment_id,";
            strQuery += " [vendor_type_id] vendor_type_id,";
            strQuery += " [vendor_id] vendor_id,";
            strQuery += " [remarks] remarks";
            strQuery += " FROM [vw_payment]";
            strQuery += " WHERE [payment_date] = '" + PCPUB.m_get_sql_date(p_date) + "'";
            strQuery += " AND [payment_id] = '" + p_id + "'";
            //
            sqlComm.Connection = sqlConn;
            sqlComm.CommandText = strQuery.ToString();
            sqlRead = sqlComm.ExecuteReader();
            //
            if (sqlRead.Read())
            {
                dt_payment_date.Value = (DateTime)sqlRead["payment_date"];
                txt_payment_id.Text = sqlRead["payment_id"].ToString();
                lst_vendor_type.SelectedIndex = lst_vendor_type.FindStringExact(PCPUB.m_get_vendor_type_name(sqlRead["vendor_type_id"].ToString()));
                lst_vendor.SelectedIndex = lst_vendor.FindStringExact(PCPUB.m_get_vendor_name(sqlRead["vendor_id"].ToString(), sqlRead["vendor_type_id"].ToString()));
                txt_remarks.Text = sqlRead["remarks"].ToString();
            }
            //
            strQuery = String.Empty;
            strQuery += " SELECT ";
            strQuery += " [tran_type_id],";
            strQuery += " [tran_type_name],";
            strQuery += " [tran_date],";
            strQuery += " [tran_id],";
            strQuery += " [amount_gross],";
            strQuery += " [amount_nett],";
            strQuery += " [amount_paid]";
            strQuery += " FROM [vw_payment_status]";
            strQuery += " WHERE [payment_date] = '" + PCPUB.m_get_sql_date(p_date) + "'";
            strQuery += " AND [payment_id] = '" + p_id + "'";
            strQuery += " ORDER BY [tran_date],[tran_id]";
            //
            sqlComm = new OleDbCommand();
            sqlComm.Connection = sqlConn;
            sqlComm.CommandText = strQuery.ToString();
            sqlRead = sqlComm.ExecuteReader();
            //
            dgv_detail.Rows.Clear();
            int r = -1;
            while (sqlRead.Read())
            {
                dgv_detail.Rows.Add();
                r++;
                dgv_detail["col_tran_date", r].Value = sqlRead["tran_date"].ToString();
                dgv_detail["col_tran_id", r].Value = sqlRead["tran_id"].ToString();
                dgv_detail["col_tran_type_id", r].Value = sqlRead["tran_type_id"].ToString();
                dgv_detail["col_tran_type_name", r].Value = sqlRead["tran_type_name"].ToString();
                dgv_detail["col_amount_gross", r].Value = sqlRead["amount_gross"].ToString();
                dgv_detail["col_amount_nett", r].Value = sqlRead["amount_nett"].ToString();
                dgv_detail["col_amount_paid", r].Value = sqlRead["amount_paid"].ToString();
                dgv_detail["col_select", r].Value = "TRUE";
            }
            //
            sqlRead.Close();
            sqlConn.Close();
            sqlRead.Dispose();
            sqlComm.Dispose();
            sqlConn.Dispose();
        }

        private void load_form()
        {
            PCPUB.m_fill_combo(lst_vendor_type, "VENDOR_TYPE");
            clear_fields(); 
        }

        private bool save_form()
        {
            try
            {
                String strQuery = String.Empty;
                ArrayList alQueries = new ArrayList();
                OleDbConnection sqlConn = new OleDbConnection();
                OleDbCommand sqlComm = new OleDbCommand();
                OleDbTransaction sqlTran;
                //
                String payment_date = String.Empty;
                String payment_id = String.Empty;
                String payment_detail_id = String.Empty;
                String user_id = String.Empty;
                String user_datetime = String.Empty;
                String vendor_type_id = String.Empty;
                String vendor_id = String.Empty;
                String tran_type_id = String.Empty;
                String tran_date = String.Empty;
                String tran_id = String.Empty;
                String amount_gross = String.Empty;
                String amount_nett = String.Empty;
                String amount_paid = String.Empty;
                String remarks = String.Empty;
                String flag_select = "FALSE";
                //
                int dgrw = 0;
                int dgrc = 0;
                //
                user_id = "'" + PCPUB.m_user_id + "'";
                user_datetime = "'" + PCPUB.m_get_sql_datetime() + "'";
                vendor_id = "'" + ((m_combo_item)lst_vendor.SelectedItem).combo_code.ToString() + "'";
                vendor_type_id = "'" + ((m_combo_item)lst_vendor_type.SelectedItem).combo_code.ToString() + "'";
                remarks = "'" + txt_remarks.Text + "'";
                //
                switch (PCPUB.m_entry_form_mode)
                {
                    case "ADDNEW":
                        payment_id = "'" + PCPUB.m_get_next_sequence("PAYMENT",dt_payment_date) + "'";
                        payment_date = "'" + PCPUB.m_get_sql_date(dt_payment_date) + "'";
                        strQuery = String.Empty;
                        strQuery += "INSERT INTO [tis_payment] (";
                        strQuery += " [payment_date],";
                        strQuery += " [payment_id],";
                        strQuery += " [user_id],";
                        strQuery += " [user_datetime],";
                        strQuery += " [vendor_type_id],";
                        strQuery += " [vendor_id],";
                        strQuery += " [remarks]";
                        strQuery += " ) VALUES (";
                        strQuery += payment_date + ",";
                        strQuery += payment_id + ",";
                        strQuery += user_id + ",";
                        strQuery += user_datetime + ",";
                        strQuery += vendor_type_id + ",";
                        strQuery += vendor_id + ",";
                        strQuery += remarks + ");";
                        alQueries.Add(strQuery);
                        break;
                    case "EDIT":
                        payment_id = "'" + PCPUB.m_record_id + "'";
                        payment_date = "'" + PCPUB.m_get_sql_date(PCPUB.m_record_date) + "'";
                        strQuery = String.Empty;
                        strQuery += "UPDATE [tis_payment] SET";
                        strQuery += " [user_id] = " + user_id + ",";
                        strQuery += " [user_datetime] = " + user_datetime + ",";
                        strQuery += " [vendor_type_id] = " + vendor_type_id + ",";
                        strQuery += " [vendor_id] = " + vendor_id + ",";
                        strQuery += " [remarks] = " + remarks;
                        strQuery += " WHERE [payment_date] = " + payment_date;
                        strQuery += " AND [payment_id] = " + payment_id + ";";
                        alQueries.Add(strQuery);
                        break;
                }
                //
                strQuery = String.Empty;
                strQuery += "DELETE FROM [tis_payment_detail] ";
                strQuery += " WHERE [payment_date] = " + payment_date;
                strQuery += " AND [payment_id] = " + payment_id + ";";
                alQueries.Add(strQuery);
                //
                dgrc = dgv_detail.Rows.Count;
                if (dgrc > 0)
                {
                    for (dgrw = 0; dgrw <= dgrc - 1; dgrw++)
                    {
                        flag_select = dgv_detail["col_select", dgrw].Value.ToString();
                        if (flag_select.Equals("TRUE"))
                        {
                            payment_detail_id = "'" + PCPUB.m_get_next_sequence("PAYMENT_DETAIL") + "'";
                            tran_type_id = "'" + dgv_detail["col_tran_type_id", dgrw].Value.ToString() + "'";
                            tran_date = "'" + PCPUB.m_get_sql_date(dgv_detail["col_tran_date", dgrw].Value.ToString()) + "'";
                            tran_id = "'" + dgv_detail["col_tran_id", dgrw].Value.ToString() + "'";
                            amount_gross = dgv_detail["col_amount_gross", dgrw].Value.ToString();
                            amount_nett = dgv_detail["col_amount_nett", dgrw].Value.ToString();
                            amount_paid = amount_nett;
                            //
                            strQuery = String.Empty;
                            strQuery += "INSERT INTO [tis_payment_detail] (";
                            strQuery += "[payment_date],";
                            strQuery += "[payment_id],";
                            strQuery += "[payment_detail_id],";
                            strQuery += "[tran_type_id],";
                            strQuery += "[tran_date],";
                            strQuery += "[tran_id],";
                            strQuery += "[amount_paid]";
                            strQuery += ") VALUES (";
                            strQuery += payment_date + ",";
                            strQuery += payment_id + ",";
                            strQuery += payment_detail_id + ",";
                            strQuery += tran_type_id + ",";
                            strQuery += tran_date + ",";
                            strQuery += tran_id + ",";
                            strQuery += amount_paid + ");";
                            alQueries.Add(strQuery);
                        }
                    }
                }
                //
                sqlConn.ConnectionString = PCPUB.m_oledb_connection.ToString();
                sqlConn.Open();
                sqlTran = sqlConn.BeginTransaction(); ;
                sqlComm.Connection = sqlConn;
                sqlComm.Transaction = sqlTran;
                //
                try
                {
                    for (int i = 0; i < alQueries.Count; i++)
                    {
                        sqlComm.CommandText = alQueries[i].ToString();
                        sqlComm.ExecuteNonQuery();
                    }
                    sqlTran.Commit();
                    PCPUB.m_payment_id = payment_id;
                }
                catch (Exception ex)
                {
                    sqlTran.Rollback();
                    PCPUB.m_payment_id = String.Empty;
                    PCMSG.ShowError(ex);
                }
                //
                sqlConn.Close();
                sqlComm.Dispose();
                sqlConn.Dispose();
                return true;
            }
            catch (Exception e)
            {
                PCMSG.Show(e.Message);
                return false;
            }
        }

        private bool validate_form()
        {
            int dgrc = 0;
            int dgrs = 0;
            int dgrw = 0;
            string flag_select = "FALSE";
            //
            dgrc = dgv_detail.Rows.Count;
            //
            if (lst_vendor_type.SelectedIndex == -1)
            {
                PCMSG.ShowError("Vendor Type field should not be empty.");
                lst_vendor_type.Focus();
                return false;
            }
            else if (lst_vendor.SelectedIndex == -1)
            {
                PCMSG.ShowError("Vendor field should not be empty.");
                lst_vendor_type.Focus();
                return false;
            }
            else if (dgrc <= 0)
            {
                PCMSG.ShowError("No transactions available for payment.");
                lst_vendor.Focus();
                return false;
            }
            else if (dgrc >= 1)
            {
                dgrs = 0;
                for (dgrw = 0; dgrw <= dgrc - 1; dgrw++)
                {
                    flag_select = dgv_detail["col_select", dgrw].Value.ToString();
                    if (flag_select.Equals("TRUE"))
                    {
                        dgrs++;
                    }
                }
                if (dgrs <= 0)
                {
                    PCMSG.ShowError("No transactions selected for payment. Please select atleast one transaction.");
                    dgv_detail.Focus();
                    return false;
                }
                else if (dgrs >= 1)
                {
                    for (dgrw = 0; dgrw <= dgrc - 1; dgrw++)
                    {
                        flag_select = dgv_detail["col_select", dgrw].Value.ToString();
                        if (flag_select.Equals("TRUE"))
                        {
                            if (dgv_detail["col_tran_date", dgrw].Value == null)
                            {
                                PCMSG.Show("Tran Date field should not be empty.");
                                dgv_detail["col_tran_date", dgrw].Selected = true;
                                return false;
                            }
                            else if (dgv_detail["col_tran_date", dgrw].Value != null
                                && dgv_detail["col_tran_date", dgrw].Value.ToString().Trim() == String.Empty)
                            {
                                PCMSG.Show("Tran Date field should not be empty.");
                                dgv_detail["col_tran_date", dgrw].Selected = true;
                                return false;
                            }
                            if (dgv_detail["col_tran_id", dgrw].Value == null)
                            {
                                PCMSG.Show("Tran Id field should not be empty.");
                                dgv_detail["col_tran_id", dgrw].Selected = true;
                                return false;
                            }
                            else if (dgv_detail["col_tran_id", dgrw].Value != null
                                && dgv_detail["col_tran_id", dgrw].Value.ToString().Trim() == String.Empty)
                            {
                                PCMSG.Show("Tran Id field should not be empty.");
                                dgv_detail["col_tran_id", dgrw].Selected = true;
                                return false;
                            }
                            if (dgv_detail["col_amount_gross", dgrw].Value == null)
                            {
                                PCMSG.Show("Amount Gross field should not be empty.");
                                dgv_detail["col_amount_gross", dgrw].Selected = true;
                                return false;
                            }
                            else if (dgv_detail["col_amount_gross", dgrw].Value != null
                                && (dgv_detail["col_amount_gross", dgrw].Value.ToString().Trim() == String.Empty
                                || double.Parse(dgv_detail["col_amount_gross", dgrw].Value.ToString().Trim()) <= 0.0))
                            {
                                PCMSG.Show("Amount Gross field should not be empty.");
                                dgv_detail["col_amount_gross", dgrw].Selected = true;
                                return false;
                            }
                            if (dgv_detail["col_amount_nett", dgrw].Value == null)
                            {
                                PCMSG.Show("Amount Nett field should not be empty.");
                                dgv_detail["col_amount_nett", dgrw].Selected = true;
                                return false;
                            }
                            else if (dgv_detail["col_amount_nett", dgrw].Value != null
                                && (dgv_detail["col_amount_nett", dgrw].Value.ToString().Trim() == String.Empty
                                || double.Parse(dgv_detail["col_amount_nett", dgrw].Value.ToString().Trim()) <= 0))
                            {
                                PCMSG.Show("Amount Nett field should not be empty.");
                                dgv_detail["col_amount_nett", dgrw].Selected = true;
                                return false;
                            }
                        }
                    }
                }
            }
            return true;
        }

        private void but_save_Click(object sender, EventArgs e)
        {
            UseWaitCursor = true;
            if (validate_form() == true)
            {
                if (save_form() == true)
                {
                    UseWaitCursor = false;
                    PCMSG.Show("Payment saved successfully. Payment Id is " + PCPUB.m_payment_id.ToString() + ".","Payment");
                    UseWaitCursor = true;
                    PCPUB.m_payment_id = String.Empty;
                    clear_fields();
                    lst_vendor_type.Focus();
                    switch (PCPUB.m_entry_form_mode)
                    {
                        case "ADDNEW":
                            break;
                        case "EDIT":
                            this.Close();
                            break;
                    }

                }
            }
            UseWaitCursor = false;
        }

        private void but_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void lst_vendor_type_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox comboBox = (ComboBox)sender;
            String tmp = String.Empty;
            try
            {
                tmp = ((m_combo_item)comboBox.SelectedItem).combo_code.ToString();
            }
            catch
            {
                tmp = "NONE";
            }
            PCPUB.m_fill_combo(lst_vendor, tmp);
        }

        private void text_id_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(char.IsLetterOrDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back))
            {
                e.Handled = true;
            }
        }

        private void text_gen_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(char.IsLetterOrDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space || e.KeyChar == '.'))
            {
                e.Handled = true;
            }
        }

        private void text_int_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back))
            {
                e.Handled = true;
            }
        }

        private void text_dec_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == '.'))
            {
                e.Handled = true;
            }
        }

        private void lst_vendor_SelectedIndexChanged(object sender, EventArgs e)
        {
            String vendor_type_id = String.Empty;
            String vendor_id = String.Empty;
            vendor_type_id = ((m_combo_item)lst_vendor_type.SelectedItem).combo_code.ToString();
            vendor_id = ((m_combo_item)lst_vendor.SelectedItem).combo_code.ToString();
            fill_form_data_addnew(vendor_type_id, vendor_id);
        }
    }

}